﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Drawing.Drawing2D;
using System.Drawing;
using Rectangle = System.Drawing.Rectangle;
using Microsoft.TeamFoundation.Common.Internal;

namespace WPFByCoreApp
{
    /// <summary>
    /// TestWriteableBitmapWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestDrawWriteableBitmapWindow : Window
    {
        private WriteableBitmap writeableBitmap;
        private List<string> fileInfos;


        public TestDrawWriteableBitmapWindow()
        {
            InitializeComponent();

            writeableBitmap = new WriteableBitmap(1920, 1080, 75, 75, PixelFormats.Bgra32, null);
            img1.Source = writeableBitmap;




            this.Loaded += TestDrawWriteableBitmapWindow_Loaded;

            fileInfos = Directory.GetFiles(@"C:\Users\41273\AppData\Roaming\Tencent\QQMusic\QQMusicCache\QQMusicPicture", "*",
                SearchOption.AllDirectories).ToList();

        }

        private void TestDrawWriteableBitmapWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(delegate
            {
                while (true)
                {
                    foreach (var file in fileInfos)
                    {
                        this.Dispatcher.Invoke(delegate { Draw(file); }, DispatcherPriority.Background);

                        Thread.Sleep(40);
                    }
                }
            });
        }

        private unsafe void Draw(string file)
        {
            writeableBitmap.Lock();
            var bm = new Bitmap(file);


            try
            {

                var buffer = RgbHelper.GetRgb32_From_Bitmap(bm);
                Int32Rect int32Rect = new Int32Rect(0, 0, bm.Width, bm.Height);

                writeableBitmap.WritePixels(int32Rect, buffer, bm.Width * 4, 0);


                writeableBitmap.AddDirtyRect(int32Rect);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                writeableBitmap.Unlock();

                Debug.WriteLine("Draw---date:" + DateTime.Now.ToString("mm:ss ff"));
            }


            //var tempBM= writeableBitmap.Resize(1920, 1080, WriteableBitmapExtensions.Interpolation.Bilinear);


            writeableBitmap.Lock();
            using (var srcContext = writeableBitmap.GetBitmapContext(ReadWriteMode.ReadWrite))
            {

                int[] temp = WriteableBitmapExtensions.Resize(srcContext, bm.Width, bm.Height, 1920, 1080,
                      WriteableBitmapExtensions.Interpolation.Bilinear);

                Int32Rect int32Rect = new Int32Rect(0, 0, 1920, 1080);

                byte[] temp1 = RgbHelper.ConverIntArrayToByteArray(temp);


                writeableBitmap.WritePixels(int32Rect, temp1, 1920 * 4, 0);
         
            }
            writeableBitmap.Unlock();


            //writeableBitmap.DrawLine(1, 2, 30, 40, Colors.Green);
            //img1.Source  = writeableBitmap.Resize(1920, 1082, WriteableBitmapExtensions.Interpolation.Bilinear);


        }
    }

    public class RgbHelper
    {

        /// <summary>
        /// Bitmap转换层RGB32
        /// </summary>
        /// <param name="Source">Bitmap图片</param>
        /// <returns></returns>
        public static byte[] GetRgb32_From_Bitmap(Bitmap Source)
        {
            return getRGBFromBMP(Source);
        }


        /// <summary>
        /// Bitmap转RGB
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static byte[] getRGBFromBMP(Bitmap bmp)
        {

            int w = bmp.Width;
            int h = bmp.Height;

            byte[] pixels = new byte[w * h * 4]; // Allocate for RGBA

            int k = 0;

            for (int x = 0; x < h; x++)
            {
                for (int y = 0; y < w; y++)
                {
                    var color = bmp.GetPixel(y, x);
                    pixels[k * 4] = color.R;
                    pixels[k * 4 + 1] = color.G;
                    pixels[k * 4 + 2] = color.B;
                    pixels[k * 4 + 3] = color.A;
                    k++;
                }
            }

            return pixels;
        }


        public static byte[] ConverIntArrayToByteArray(int[] ints)
        {
            byte[] buffer = new byte[ints.Length * 4];

            for (int i = 0; i < ints.Length; i++)
            {
                buffer[i * 4] = (byte)(ints[i] >> 24);
                buffer[i * 4 + 1] = (byte)(ints[i] >> 16);
                buffer[i * 4 + 2] = (byte)(ints[i] >> 8);
                buffer[i * 4 + 3] = (byte)(ints[i]);
            }


            return buffer;
        }



        ///// <summary>
        ///// Bitmap转换层RGB32
        ///// </summary>
        ///// <param name="Source">Bitmap图片</param>
        ///// <returns></returns>
        //public static byte[] GetRgb32_From_Bitmap(Bitmap Source, ref bool bError, ref string errorMsg)
        //{
        //    bError = false;

        //    int lPicWidth = Source.Width;
        //    int lPicHeight = Source.Height;

        //    Rectangle rect = new Rectangle(0, 0, lPicWidth, lPicHeight);
        //    System.Drawing.Imaging.BitmapData bmpData = Source.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, Source.PixelFormat);
        //    IntPtr iPtr = bmpData.Scan0;

        //    int picSize = lPicWidth * lPicHeight * 4;

        //    byte[] pRrgaByte = new byte[picSize];

        //    System.Runtime.InteropServices.Marshal.Copy(iPtr, pRrgaByte, 0, picSize);

        //    Source.UnlockBits(bmpData);

        //    int iPoint = 0;
        //    int A = 0;

        //    try
        //    {
        //        //for (int iRow = 0; iRow < lPicHeight; iRow++)
        //        //{
        //        //    for (int jCol = 0; jCol < lPicWidth; jCol++)
        //        //    {
        //        //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 0] = Convert.ToByte(pRrgaByte[iPoint++]);
        //        //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 1] = Convert.ToByte(pRrgaByte[iPoint++]);
        //        //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 2] = Convert.ToByte(pRrgaByte[iPoint++]);
        //        //        pRrgaByte[4 * (iRow * lPicWidth + jCol) + 3] = Convert.ToByte(A);
        //        //    }
        //        //}

        //        bError = true;
        //        errorMsg = "BMP数据转换成功";

        //        return pRrgaByte;
        //    }
        //    catch (Exception exp)
        //    {
        //        pRrgaByte = null;

        //        bError = false;
        //        errorMsg = exp.ToString();
        //        //throw;
        //    }

        //    return null;
        //}
    }
}
